﻿using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;

namespace TTprotons.Crm.JavascriptAudit.Common
{
    public static class ZipStreamHelper
    {
        private const int STREAM_SIZE = 2048;

        public static string ExtractTextFile(byte[] sourceFile, string textFileName, Encoding encoding)
        {
            using (var sourceMS = new MemoryStream(sourceFile))
            {
                using (var zis = new ZipInputStream(sourceMS))
                {
                    ZipEntry entry;
                    while ((entry = zis.GetNextEntry()) != null)
                    {
                        if (!entry.Name.ToLower().Equals(textFileName.ToLower())) continue;

                        var ms = new MemoryStream();

                        var data = new byte[STREAM_SIZE];
                        while (true)
                        {
                            var size = zis.Read(data, 0, data.Length);
                            if (size <= 0)
                                break;

                            ms.Write(data, 0, size);
                        }

                        var extractedFile = ms.ToArray();
                        return encoding.GetString(extractedFile);
                    }
                }
            }

            return string.Empty;
        }
    }
}